package cn.sy.exception;

import cn.sy.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.error("发生系统异常，异常信息为：" + e.getMessage());
        return JSONResult.error(GlobalErrorCodeEnum.SERVICE_ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult GlobalCustomException(GlobalCustomException e){
        e.printStackTrace();
        log.error("发生系统异常，异常信息为：" + e.getMessage());
        return JSONResult.error(e);
    }

    /**
     * 参数校验
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult GlobalCustomException(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.error("发生系统异常，异常信息为：" + e.getMessage());
        List<ObjectError> result = e.getBindingResult().getAllErrors();
        StringBuffer sb = new StringBuffer();
        sb.append("参数校验失败， 失败原因为:");
        for (ObjectError objectError : result) {
            sb.append(objectError.getDefaultMessage()).append(";");
        }
        return JSONResult.error(sb.toString(), GlobalErrorCodeEnum.SERVICE_PARAM_JSR303_ERROR.getCode());
    }
}
